#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""
service
"""
WORKERS=10

import tornado.ioloop
import tornado.web
import config.glob_conf as config
import traceback

from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor
from scpy.logger import get_logger
from tornado.web import HTTPError


import json
from stompest.config import StompConfig
from stompest.protocol import StompSpec
from stompest.sync import Stomp
import utils

MESSAGE_NUMBERS = 1


QUEUE_DICT = {
    'cq':'/queue/saic_cq',
    'tj':'/queue/saic_tj',
    'sc':'/queue/saic_sc',
    'gd':'/queue/saic_gd',
    'hn':'/queue/saic_hn',
    'js':'/queue/saic_js',
    'nmg':'/queue/saic_nmg',
    'yn':'/queue/saic_yn',
    'hlj':'/queue/saic_hlj',
    'hen':'/queue/saic_hen',
    'ah':'/queue/saic_ah',
    'gx':'/queue/saic_gx',
    'bj':'/queue/saic_bj',
    'ln':'/queue/saic_ln',
    'xj':'/queue/saic_xj',
    'jx':'/queue/saic_jx',
    'sd':'/queue/saic_sd',
    'fj':'/queue/saic_fj',
    'gs':'/queue/saic_gs',
    'jl':'/queue/saic_jl',
    'hb':'/queue/saic_hb',
    'sx':'/queue/saic_sx',
    'qh':'/queue/saic_qh',
    'xz':'/queue/saic_xz',
    'sax':'/queue/saic_sax',
    }


logger = get_logger(__file__)
class SaicWindowsHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(max_workers=WORKERS)

    @run_on_executor
    def get(self):
        """
        根据省份从q里拿名字
        """
        province = self.request.get_param('province')

        if not province or province not in QUEUE_DICT.keys():
            raise HTTPError(400,'province is null or wrong')
        queue = QUEUE_DICT.get(province)
        CONFIG = StompConfig(config.QUEUE_URI)
        client = Stomp(CONFIG)
        client.connect()
        client.subscribe(queue, {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL,'activemq.prefetchSize':1})
        name_list = []
        for index in range(MESSAGE_NUMBERS):
            try:
                frame = client.receiveFrame()
                data = json.loads(frame.body)
                logger.info(data.get('key'))
                name_list.append(data)
                client.ack(frame)
            except Exception,e:
                print frame.body
                logger.exception(e)
                client.ack(frame)
                continue
            if not province:
                client.ack(frame)
                continue
        self.write(json.dumps(name_list))


    @run_on_executor
    def post(self):
        requests_data = json.loads(self.request.body)
        data = requests_data.get('data',{})
        company_name= requests_data.get('companyName')
        exception = data.get('exception','')
        if exception:
            logger.info('exception:%s'%company_name)
            utils.save_data((),company_name,'exception')
            raise HTTPError(404,'exception')
        if not data:
            logger.info('no data:%s'%company_name)
            utils.save_data((),company_name,'notvalue')
            raise HTTPError(404,'no data')
        try:
            print json.dumps(data,ensure_ascii=False)
            utils.save_data(data,company_name,'value')
        except Exception,e:
            err = traceback.format_exc(e)
            logger.exception(err)
            raise HTTPError(500,'save error')


application = tornado.web.Application([
    (r"/saic", SaicWindowsHandler),
])


if __name__ == "__main__":
    application.listen(7375)
    logger.info('server start')
    tornado.ioloop.IOLoop.instance().start()
